import { delContent, findAllList } from '@/api/draft';
import type { TContent } from '@/api/draft/type';
import { ResultCodeEnum } from '@/enums';
import { jump } from '@/utils/common';
import { useMessage, useToast } from 'wot-design-uni';

export const useDraft = () => {
  const tab = ref(0);
  const tabList = [
    {
      label: '当前计划',
      value: 0
    },
    {
      label: '历史计划',
      value: 1
    }
  ];
  const handlePreview = (item: TContent) => {
    jump(`/pages/moments/preview/index?id=${item.id}`);
  };

  const list = ref<TContent[]>([]);
  const doneList = ref<TContent[]>([]);
  const todoList = ref<TContent[]>([]);

  watch(
    () => tab.value,
    (val) => {
      list.value = val ? doneList.value : todoList.value;
    }
  );
  const getAllList = async () => {
    doneList.value = [];
    todoList.value = [];
    const res = await findAllList();
    if (res.code === ResultCodeEnum.SUCCESS) {
      res.data.forEach((item) => {
        if (item.isDone) {
          doneList.value.push(item);
        } else {
          todoList.value.push(item);
        }
      });
      list.value = tab.value ? doneList.value : todoList.value;
    }
  };
  const { success: showSuccess } = useToast();
  const message = useMessage();
  const handleDel = async (id: number) => {
    message
      .confirm({
        msg: '是否确认删除',
        title: '删除提示'
      })
      .then(async () => {
        const res = await delContent(id);
        if (res.code === ResultCodeEnum.SUCCESS) {
          showSuccess({
            msg: '删除成功'
          });
        }
        getAllList();
      })
      .catch(() => {
        console.log('点击了取消按钮');
      });
  };

  onMounted(() => {
    getAllList();
  });

  return {
    tab,
    tabList,
    list,
    handleDel,
    handlePreview
  };
};
